package net.daum.mail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.event.WriteListener;

import org.apache.commons.lang.StringUtils;

public class SMTPClient {

	private String host;
	private String userid;
	private String password;
	private String port;
	private String security;
	private Session session;
	private WriteListener listener;

	public SMTPClient(String host, String userid, String password, String port, String security) {
		this.host = host;
		this.userid = userid;
		this.password = password;
		this.port = port;
		this.security = security;
	}
	
	public Session getSession() {
		return getSession(false);
	}
	
	public Session getSession(boolean debug) {
		if (session == null) {
			session = createSession(debug);
		}
		return session;
	}
	
	private Session createSession(boolean debug) {
		Properties props = new Properties();
		if (StringUtils.equals("tls", security)) {
			props.setProperty("mail.smtp.starttls.enable", "true");
		} else if (StringUtils.equals("ssl", security)) {
			props.setProperty("mail.smtp.ssl.enable", "true");
			props.setProperty("mail.smtp.ssl.trust", "*");
			props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		}
		
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.smtp.host", host);
		props.setProperty("mail.smtp.port", port);
		props.setProperty("mail.smtp.socketFactory.port", port);
		props.setProperty("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.debug", String.valueOf(debug));
		props.setProperty("mail.debug.auth", String.valueOf(debug));
		
		Session session = null;
		if(userid != null){
			props.setProperty("mail.smtp.auth", "true");
			session = Session.getInstance(props, new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(userid, password);
				}
			});
		} else {
			session = Session.getDefaultInstance(props);
		}
		session.setDebug(debug);
		
		return session;
	}
	
	public WriteListener getListener() {
		return listener;
	}

	public void setListener(WriteListener listener) {
		this.listener = listener;
	}

	public boolean checkConnection() throws MessagingException {
		Session session = getSession();
		Transport transport = null;
		try {
			transport = session.getTransport();
			transport.connect();
		} finally {
			try {
				if (transport != null) {
					transport.close();
				}
			} catch (MessagingException me) {
			}
		}
		return true;
	}
	
	public void send(Message message) throws MessagingException {
		Transport.send(message, listener);
	}
}
